package redis;

import com.alibaba.fastjson.JSONObject;
import entity.custom.CustomText;
import entity.custom.Text;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import service.WxServiceImpl;
import service.api.ai.AiService;
import util.Request;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Slf4j
public class MessageConsumerText implements Runnable {
    static InputStream in = MessageConsumerImage.class.getClassLoader().getResourceAsStream("wx-config.xml");
    static Map<String, String> Xmlmap = WxServiceImpl.parseRequest(in);
    private static final String CustomSend=Xmlmap.get("customSend");
    static JedisConnectPool jedisPool = new JedisConnectPool();
    static Jedis jedis=jedisPool.getJedis();
    static Jedis jedis2=jedisPool.getJedis();
    public static final String CHANNEL_KEY2 = "task_que2";//频道

    private final MyJedisPubSub2 jedisPubSub2 = new MyJedisPubSub2();

    public void consumerMessage() {
        jedis2.psubscribe(jedisPubSub2, CHANNEL_KEY2);
    }

    @Override
    public void run() {
//        while (true) {
        consumerMessage();
//        }
    }

    protected static void singleChat(String message){
        String[] s = message.split(":");

        String ask = s[1];
        String customSendUrl = CustomSend.replace("ACCESS_TOKEN", WxServiceImpl.getAccessToken());
        String response;
        try {
            response = AiService.singleChat(ask);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if(e.getMessage().contains("code: 429"))
                response="请求过于频繁，请稍后再次发送";
            else
                response = "脑子抽筋了，请帮我联系鑫哥谢谢！";
        }
        String sendData = JSONObject.toJSONString(new CustomText(s[0], new Text(response)));
        log.info("sendData  :" + sendData);
        String res = Request.sendPost(customSendUrl, sendData);
        log.info("customRes  :" + res);
    }

    private static String parseChat(String role,String message){
        return "{\"role\": \""+ role +"\",\"content\": \""+ message +"\"}";
    }

    protected static void continuousChat(String message){
        String[] s = message.split(":");
        String ask = s[1];

        jedis.rpush("continuousChat:"+s[0],parseChat("user",ask));
        List<String> chatArray=jedis.lrange("continuousChat:"+s[0],0,-1);
//        log.info(chatArray.toString());

        String customSendUrl = CustomSend.replace("ACCESS_TOKEN", WxServiceImpl.getAccessToken());
        String response;
        try {
            response = AiService.continuousChat(chatArray.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if(e.getMessage().contains("code: 429"))
                response="请求过于频繁，请稍后再次发送";
            else
                response = "脑子抽筋了，请帮我联系鑫哥谢谢！";
        }
        String sendData = JSONObject.toJSONString(new CustomText(s[0], new Text(response)));
        log.info("sendData  :" + sendData);
        String res = Request.sendPost(customSendUrl, sendData);
        log.info("customRes  :" + res);
        int code=JSONObject.parseObject(res).getIntValue("errcode");
        if (!response.equals("脑子抽筋了，请帮我联系鑫哥谢谢！")&&!response.equals("请求过于频繁，请稍后再次发送")&&code==0)
            jedis.rpush("continuousChat:"+s[0],parseChat("assistant",response));
        jedis.expire("continuousChat:"+s[0],181);
    }

    static class MyJedisPubSub2 extends JedisPubSub {

        @Override
        public void onPMessage(String pattern, String channel, String message) {
//            System.out.println(Thread.currentThread().getName() + "-接受到的消息:pattern"+pattern+",channel:"+channel+",message:"+message);

//            MessageConsumerText.singleChat(message);
            MessageConsumerText.continuousChat(message);

        }
    }
}